package org.goodsl.mdd;

import java.util.HashMap;
import org.goodsl.mdd.annotation.Setting;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-11-20
 * Time: 上午9:56
 * To change this template use File | Settings | File Templates.
 */
public class TypeSetting implements Cloneable {

    public TypeSetting(Setting setting)throws ParseException {
        reset(setting);
    }

    public TypeSetting() {}

    public void reset(Setting setting)throws ParseException{
        this.alias = setting.alias();
        this.desc = setting.desc();
        this.nullable = setting.nullable();
        parseMap(setting.map());
    }

    private void parseMap(String mapStr)throws ParseException {
        if (!mapStr.startsWith("[") || !mapStr.endsWith("]")) {
            throw new ParseException("Annotation Setting's map format must be '[k1:v1,k2:v2]' style");
        }

        //去掉首尾的'[]'
        String str = mapStr.substring(1, mapStr.length() - 1);
        String[] kvList = str.split(",");
        if (props == null)
            props = new HashMap<String, String>(kvList.length);
        for(String kvStr :kvList){
            String[] kv = kvStr.split(":");
            if (kv.length == 2) {
               props.put(kv[0],kv[1]);
            }
        }

    }

    String propertyMissing(String name) {
        if (props == null || !props.containsKey(name))
            return "";
        else
            return props.get(name);
    }

    private HashMap<String, String> props;

    private String alias = "";

    public String getAlias() {
        return alias;
    }
    protected void setAlias(String alias){
        this.alias = alias;
    }

    private String desc = "";

    public String getDesc() {
        return desc;
    }

    private boolean nullable = false;

    public boolean getNullable() {
        return nullable;
    }

    public Object clone() {
        TypeSetting newOne = new TypeSetting();
        newOne.alias = this.alias;
        newOne.desc = this.desc;
        newOne.nullable = this.nullable;
        if (props != null && props.size() > 0) {
            for(String key : props.keySet()){
                newOne.props.put(key,props.get(key));
            }
        }

        return newOne;
    }
}
